package log.logaspect;

import javax.annotation.Resource;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import log.entity.LogForService;
import log.service.servicelog.IServiceLogService;
import util.MYUtil;
import util.MyConfig;

@Component
@Aspect
public class ServiceLogAspect {
	@Resource
	private IServiceLogService serviceLogServiceImpl;
	@Resource
	private MyConfig myConfig;

	public ServiceLogAspect() {
		MYUtil.printMyLog("---ServiceAspect----", MYUtil.NOT_SHOW_SINGLE);
	}

	@Pointcut("execution(* service..*.*(..))")
	public void pointCut() {
	}

	@Around("pointCut()")
	public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
		long begin = System.currentTimeMillis();
		Object obj = proceedingJoinPoint.proceed();
		long end = System.currentTimeMillis();
		int useTime = (int) (end - begin);
		if (myConfig.getRecordServiceLog()) {
			String packageName = proceedingJoinPoint.getTarget().getClass().getName();
			String className = proceedingJoinPoint.getSignature().getName();
			String fullClassName = packageName + "." + className;
			LogForService logForService = new LogForService(fullClassName, useTime, false, "");
			serviceLogServiceImpl.save(logForService);
		}
		return obj;
	}

	@AfterThrowing(pointcut = "pointCut()", throwing = "error")
	public void afterThrowing(JoinPoint joinPoint, Exception error) {
		if (myConfig.getRecordServiceLog()) {
			String packageName = joinPoint.getTarget().getClass().getName();
			String className = joinPoint.getSignature().getName();
			String fullClassName = packageName + "." + className;
			String exceptionName = error.getClass().getName();
			LogForService logForService = new LogForService(fullClassName, 0, true, exceptionName);
			try {
				serviceLogServiceImpl.save(logForService);
			} catch (Exception e) {
				System.out.println("记录service层异常日志出错");
				e.printStackTrace();
			}
		}
	}
}
